package Netzwerk;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 * Class to transform a File into a Byte Array
 * @author z0030vku
 *
 */
public class FileAsByteArray {
 
	public static File file; 
	public static byte[] bytes;
	public String dateiName;
	
	public FileAsByteArray(File file, String dateiName) throws FileNotFoundException{
		this.file 		= file;
		this.dateiName	= dateiName;
		this.FileToByte();
	}
    
	public FileAsByteArray(byte[] bytes, String dateiName) throws IOException{
		this.dateiName	= dateiName;
		this.ByteToFile(bytes, dateiName);
	}
	
	/**
	 * Transform File to Byte Array
	 */
    public void FileToByte() throws FileNotFoundException{
    	FileInputStream fis = new FileInputStream(file);
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
          //  Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        bytes = bos.toByteArray();
    }
    
    /**
     * transform Byte Array to File
     * @param bytes
     * @param dateiName
     * @throws IOException
     */
    public void ByteToFile(byte[] bytes, String dateiName) throws IOException{
        File someFile = new File(dateiName);
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
        this.file = someFile;
    }
} 